<template>
 
    <!-- 工具栏 
    <vxe-toolbar v-if="showVxeToolbar" class="flex-shrink-0">
      <template #buttons><slot name="toolbar-left" /></template>
      <template #tools><slot name="toolbar-right" /></template>
    </vxe-toolbar>


-->

    <!-- 2. 表格：所有属性写进开始标签 -->
    <vxe-grid
      ref="xTable"
      class="flex-1"
      :stripe="props.stripe"
      :border="props.border"
      :row-class-name="props.rowClassName ?? tableRowClassName"
      :data="currentPageData"
      :loading="loading"
      :row-config="localRowConfig"
      :column-config="{ resizable: true, drag: true }"
      :column-drag-config="{ trigger: 'cell', showIcon: false }"
      :sort-config="sortConfig"
      :checkbox-config="localCheckboxConfig"
      :edit-config="editConfig"
      :toolbarConfig="localToolbarConfig"
      :export-config="exportConfig" 
      :print-config="printConfig"
      :columns="processedColumns"
      @checkbox-change="handleSelectionChange"
      @checkbox-all="handleSelectionChange"
      @cell-dblclick="handleCellDbClick"
      @row-dblclick="handleRowDbClick"
      @row-click="handleRowClick"
      @cell-click="handleCellClick"
      @sort-change="handleSortChange"
    >
    <template #toolbarButtons> 
      <div class="flex items-center h-32px    leading-32px -mt-6px">       
                <!-- 1. 内置搜索栏 -->
          <el-input
          v-if="showSearch"
            v-model="keyword"
            :placeholder="$t('placeholder.keyword')"
            clearable
            class="w-180px"
             
            @clear="onClear"
            @keyup.enter="onSearch"
          > 
          </el-input>
          <div class="flex items-center gap-8px ml-8px">
            <slot name="toolbar-left" />
          </div>
       </div>
      </template>
 
      <!-- 操作列插槽 -->
      <template #operate="{ row }" v-if="$slots.operate">
        <slot name="operate" :row="row" />
      </template>
    </vxe-grid>

    <!-- 分页：直接绑定父组件 page 对象 -->
    <vxe-pager
      v-if="showPager"
      class="flex-shrink-0"
      v-bind="localPage"
      :layouts="pagerLayouts"
      @page-change="onPageChange"
    />
 
</template>

<script setup lang="ts">
import type { PropType } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ref, computed, useSlots ,onMounted} from 'vue'
import type {
  VxeGridInstance,
  VxeGridPropTypes,
  VxeTablePropTypes,
   VxeTableInstance,
   VxeTableDefines,
  VxeGridEvents,
  VxeGridProps
} from 'vxe-table'
import type { VxePagerEvents, VxePagerPropTypes } from 'vxe-pc-ui'
import type {Column,PageInfo,ExportConfig} from '@/types'
import {strDateTime} from '@/utils'
 



/* ---------- props ---------- */
const props = defineProps({
  tableColumns: { type: Array as PropType<Column[]>, required: true },
  tableData: { type: Array as PropType<any[]>, default: () => [] },
  fullData: { type: Array as PropType<any[]>, default: () => [] },
  showSearch: { type: Boolean, default: true },
  page: {
    type: Object as PropType<PageInfo>,
    default: () => ({
      currentPage: 1,
      pageSize: 20,
      pageSizes: [10, 20, 50, 100],
      total: 0
    })
  },
  pagerLayouts: {
    type: Array as PropType<VxePagerPropTypes.Layouts>,
    default: () => ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']
  },
  rowConfig: {
    type: Object as PropType<VxeGridProps['rowConfig']>,
    default: () => ({ isHover: true, keyField: 'id' })
  },
  showPager: { type: Boolean, default: true },
  height: { type: String, default: '600px' },
  showVxeToolbar: { type: Boolean, default: false },
  operateWidth: { type: Number, default: 120 },
  rowKey: { type: String, default: 'id' },
  loading: { type: Boolean, default: false },
  stripe: { type: Boolean, default: false },
  border: { type: Boolean, default: true },
  treeConfig: {
    type: Object as PropType<VxeTablePropTypes.TreeConfig>,
    default: () => ({})
  },
  rowClassName: { type: Function as PropType<(params: any) => string> },
  sortConfig: { type: Object as PropType<VxeTablePropTypes.SortConfig>, default: () => ({ remote: false }) },
  checkboxConfig: {
    type: Object as PropType<VxeTablePropTypes.CheckboxConfig>,
    default: (): VxeTablePropTypes.CheckboxConfig => ({
      highlight: true,
      range: true
    })
  },
  editConfig: { type: Object as PropType<VxeTablePropTypes.EditConfig> }
})

/* ---------- emit ---------- */
const emit = defineEmits([
  'update:page',
  'selection-change',
  'sort-change',
  'row-dblclick',
  'cell-dblclick',
  'row-click',
  'cell-click'
])

/* ---------- 配置文件 ---------- */
const localRowConfig = computed(() => ({
  isHover: true,
  keyField: 'id',
  drag: true,
  useKey: true,
  ...props.rowConfig
}))

 
const localToolbarConfig = computed(() => ({
  custom: true,// 是否完全自定义整个 toolbar 渲染
  refresh: true,// 显示「刷新」按钮
  zoom: true, // 显示「全屏/缩放」按钮
  export: true, // 显示「导出」按钮

  print: true,  // 是否显示「打印」按钮
  slots: {
      buttons: 'toolbarButtons'
    }
}))

const localTreeConfig = computed(() => ({
  transform: true,
  rowField: 'id',
  parentField: 'parentId',
  ...props.treeConfig
}))

const localCheckboxConfig = computed(() => {
  const isTree = !!props.treeConfig?.children || !!props.treeConfig?.transform
  return {
    ...(isTree ? { range: false } : {}),
    ...props.checkboxConfig
  }
})

const localPage = ref({
  currentPage: props.page.currentPage,
  pageSize: props.page.pageSize,
  pageSizes: props.page.pageSizes,
  total: props.page.total
})

const exportConfig = ref({
  types: ['csv', 'html', 'txt', 'xlsx'],
  // 默认导出类型
  type: 'xlsx',                 // 默认选中 xlsx
  filename: ({ $table }) => `导出_${strDateTime()}`,
    // 是否自动下载
  download: true,
  useStyle: true,
  isMerge: true
})
/*
const exportConfig = ref<ExportConfig>({
  modes: ['current', 'selected', 'all'],
  types: ['csv', 'html', 'txt', 'xlsx'],
  // 默认导出类型
  type: 'xlsx',
  // 原始字段名还是格式化后的文本
  original: false,
  // 是否自动下载
  download: true,
  // 文件名模板
  filename: ({ $table }) => `导出_${strDateTime()}`,
  columnFilterMethod: col => col.field !== 'operate', // 隐藏操作列
  isHeader: true,
  isFooter: false,
  useStyle: true,          // xlsx 带样式
  sheetName: '数据',
  beforeExportMethod: async ({ $table }) => {
    // 例：导出前再刷一次最新数据
    // await loadLatest()
    return true
  }
})
  */

const printConfig = {
  mode: 'all',
  isHeader: true,
  isFooter: false,
  landscape: true,
  fontSize: 13,
  title: '数据列表',
  sheetName:'数据列表',
  columnFilterMethod: col => !['operate', 'avatar'].includes(col.field),
  style: `
    .vxe-table--print td,th{border-color:#ccc}
    .vxe-table--print thead th{background:#f0f0f0}
  `
}
 
/* ---------- 计算属性 ---------- */
const slots = useSlots()
const xTable = ref<VxeGridInstance>()


const processedColumns = computed<VxeGridPropTypes.Columns>(() => {
  //const cols: VxeGridPropTypes.Columns = (props.tableColumns ?? []).map(col => {
  // const cols: VxeGridPropTypes.Columns = props.tableColumns.map(col => {
    const cols: VxeGridPropTypes.Columns = (props.tableColumns ?? [])
    .filter(col => !col.hide) // 👈 新增
    .map(col => {
    const item: any = { ...col }
    if (col.is_filter && col.field) {
      const dataSource = props.tableData.length ? props.tableData : []
      const unique = Array.from(new Set(dataSource.map((i: any) => i[col.field])))
        .filter(v => v != null)
        .map(v => ({ label: String(v), value: v }))
      item.filters = unique
      item.filterMethod = ({ value, row }: any) => value == null || row[col.field] == value
    }
    if ((col as any).field && slots[(col as any).field]) {
      item.slots = { default: ({ row }: any) => slots[(col as any).field]?.({ row }) }
    }
    return item
  })
  if (slots.operate) {
    cols.push({ title: '操作', fixed: 'right', width: props.operateWidth, slots: { default: 'operate' } })
  }
  return cols
})

/* ---------- 搜索属性与事件 ---------- */
const keyword = ref('')
/* 过滤后的全量数据 */
const filteredData = computed(() => {
 
  const kw = keyword.value.trim().toLowerCase()
  // 1. 先拿到过滤后的数组
  const list = !kw
    ? props.tableData
    : props.tableData.filter((v: any) =>
        Object.values(v)
          .filter(val => val !== null && val !== undefined)
          .some(val => String(val).toLowerCase().includes(kw))
      )

  // 2. 关键：把总条数实时同步给父组件
  //    只要搜索关键字变化，这里就会重新执行
  localPage.value.total = list.length
  localPage.value.currentPage = 1
  return list
})

/* 搜索 / 清空 */
function onSearch() {
  /* 只要关键字变化，filteredData 会自动重新计算；
     把页码拉回第一页即可 */
  emit('update:page', { ...props.page, currentPage: 1 })
}
function onClear() {
  keyword.value = ''
  emit('update:page', { ...props.page, currentPage: 1 })
}

/* 总条数 = 过滤后 */
const total = computed(() => filteredData.value.length)

/* ---------- 事件处理 ---------- */
const handleSelectionChange: VxeGridEvents.CheckboxChange | VxeGridEvents.CheckboxAll = () => {
  const records = xTable.value?.getCheckboxRecords() ?? []
  emit('selection-change', records)
}
/*
const onPageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
  emit('update:page', { ...props.page, currentPage, pageSize })
}
  */
const onPageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
  localPage.value.currentPage = currentPage
  localPage.value.pageSize = pageSize
  //emit('update:page', { ...props.page, currentPage: 1, total: list.length })
}
const handleCellDbClick: VxeGridEvents.CellDblclick = ({ row, column, cell, $event }) => {
  console.log('cell double clicked:', row, column, cell, $event)
  emit('cell-dblclick', row, column, cell, $event)
}
const handleRowDbClick: any = ({ row, $event }) => {
  console.log('row double clicked:', row, $event)
  emit('row-dblclick', row, $event)
}
const handleRowClick = ({ row, $event }) => {
  console.log('row clicked:', row, $event)
  emit('row-click', row, $event)
}
const handleCellClick: VxeGridEvents.CellClick = ({ row, column, cell, $event }) => {
   
  emit('cell-click', row, column, cell, $event)
}
const handleSortChange: VxeGridEvents.SortChange = (params) => {
  emit('sort-change', params)
}

/* ---------- 新增：当前页数据 ---------- */
const currentPageData = computed(() => {
  const { currentPage, pageSize } =localPage.value // props.page
  const start = (currentPage - 1) * pageSize
  const end = start + pageSize
  return filteredData.value.slice(start, end)
  //return props.tableData.slice(start, end)   // 本地分页核心
})

function tableRowClassName({ rowIndex }: any) {
  return rowIndex % 2 === 0 ? 'bg-gray-50' : 'bg-white'
}




/* ---------- 暴露方法 ---------- */
defineExpose({
  getTableRef: () => xTable.value,
  getCheckboxRecords: () => xTable.value?.getCheckboxRecords() ?? [],
  clearCheckboxRow: () => xTable.value?.clearCheckboxRow()
})
</script>
<style  scoped>
/* 导出弹窗整体缩小 */
:deep(.vxe-table-export-popup-wrapper) {
  width: 360px !important;
  height: 240px !important;
   background: #fcc; /* 调完可删 */
}
/* 内容区滚动 → 确认按钮常驻 */
:deep(.vxe-table-export-popup-wrapper .vxe-modal--body) {
  max-height: calc(100% - 110px) !important;
  overflow-y: auto;
}
</style>